using Chaotic.DataBase.DataAccess;
using Chaotic.DataBase.DBAccessLibrary.Common;
using Chaotic.DataBase.DBAccessLibrary.Interface;
using Chaotic.DataBase.DBAccessLibrary.Model;
using System.Reflection;

namespace Chaotic.DataBase.DBAccessLibrary.DBAccessLibrary;

public static class DBOperatorFactory
{
	public static IOperations GetOperator
	{
		get
		{
			IOperations? operations = MemoryCacheManager.GetCache<DatabaseOperations>("DatabaseOperations");
			if (operations == null)
			{
				operations = new DatabaseOperations();
                MemoryCacheManager.SetCache("DatabaseOperations", operations, 30);
			}
			return operations;
		}
	}

	public static IGrammar? GetGrammar(ConnectionModel? connect)
	{
		if (connect != null)
		{
            Assembly assembly = DataAccessFactory.Instance.GetAssemblyPath(connect.ConnectType);
            IEnumerable<Type> GrammarAccessInstance = DataAccessFactory.Instance.GetClassesImplementingInterface<IGrammar>(assembly);
            if(GrammarAccessInstance.Any())
			{
                Type dbtype = GrammarAccessInstance.First(); 
                return dbtype.CreateInstance<IGrammar>([typeof(ConnectionModel)],[connect]);
            }
        }
		return null;
	}

	internal static ILocalGrammar GetLocalGrammar(ConnectionModel? connect)
	{
		return (ILocalGrammar)GetGrammar(connect)!;
	}



    public static ISqlKeyword GetSqlKeywords(ConnectionModel? connect)
    {
        if (connect != null)
        {
            Assembly assembly = DataAccessFactory.Instance.GetAssemblyPath(connect.ConnectType);
            IEnumerable<Type> GrammarAccessInstance = DataAccessFactory.Instance.GetClassesImplementingInterface<ISqlKeyword>(assembly);
            if (GrammarAccessInstance.Any())
            {
                Type dbtype = GrammarAccessInstance.First();
                return dbtype.CreateInstance<ISqlKeyword>();
            }
        }
		return new DefaultSqlKeyword();
    }
}
